package com.shop.controller;

import com.shop.entity.UserInfo;
import com.shop.service.UserService;
import com.shop.util.ResultUtil;
import com.shop.vo.ResultVo;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author denpeng
 * @create 2018-05-24 13:54
 **/
@RestController
@RequestMapping("login")
public class UserController {

  private final UserService userService;

  private final HttpServletResponse response;

  private final StringRedisTemplate redisTemplate;

  private final HttpServletRequest request;

  @Autowired
  public UserController(UserService userService, HttpServletResponse response, StringRedisTemplate redisTemplate,
      HttpServletRequest request) {
    this.userService = userService;
    this.response = response;
    this.redisTemplate = redisTemplate;
    this.request = request;
  }

  /**
   * 买家登陆
   *
   * @param openid openid
   */
  @RequestMapping(value = "buyer", method = RequestMethod.GET)
  public ResultVo buyer(@RequestParam("openid") String openid) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0 && cookies[0] != null && cookies[0].getValue().equals("abc")) {
      return ResultUtil.success(null);
    }

    UserInfo userInfo = userService.selectByOpenid(openid);
    if (userInfo == null) {
      return ResultUtil.error();
    }

    if (userInfo.getRole() != 1) {
      return ResultUtil.error();
    }
    Cookie cookie = new Cookie("openid", "abc");
    cookie.setMaxAge(7200);
    response.addCookie(cookie);
    return ResultUtil.success(null);
  }

  /**
   * 卖家登陆
   *
   * @param openid openid
   */
  @RequestMapping(value = "seller", method = RequestMethod.GET)
  public ResultVo seller(@RequestParam("openid") String openid) {
    Cookie[] cookie = request.getCookies();
    if (cookie != null && cookie.length > 0 && cookie[0] != null) {
      if (StringUtils.isNotBlank(redisTemplate.opsForValue().get(cookie[0].getValue()))) {
        return ResultUtil.success(null);
      }
    }
    UserInfo userInfo = userService.selectByOpenid(openid);
    if (userInfo == null) {
      return ResultUtil.error();
    }
    if (userInfo.getRole() != 2) {
      return ResultUtil.error();
    }
    String uuid = UUID.randomUUID().toString();
    response.addCookie(new Cookie("token", uuid));
    redisTemplate.opsForValue().set(uuid, "xyz");
    return ResultUtil.success(null);
  }
}
